package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;

    /*
     * 分页查询(基本信息)
     * */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name) {
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Setmeal::getName, name);
        wrapper.orderByDesc(Setmeal::getUpdateTime);

        //根据条件查询放入wrapper
        setmealService.page(pageInfo, wrapper);

//--------------------------------------------------------------------------
        /*
         * 完善查询
         *
         * */
        Page<SetmealDto> dtoPage = new Page<>();
        //封装数据total
        dtoPage.setTotal(pageInfo.getTotal());
        //封装数据records
        List<Setmeal> records = pageInfo.getRecords();//原始的数据列表
        List<SetmealDto> list = records.stream().map((setmeal) -> {
            SetmealDto setmealDto = new SetmealDto();
            //对象拷贝
            BeanUtils.copyProperties(setmeal, setmealDto);

            //根据id查询
            Category category = categoryService.getById(setmeal.getId());
            if (category != null) {
                setmealDto.setCategoryName(category.getName());//分类的名称
            }
            return setmealDto;
        }).collect(Collectors.toList());
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /*
     * 新增套餐
     * */
    @CacheEvict(value ="setmealCache",allEntries = true )
    @PostMapping
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info("套餐信息，{}", setmealDto);
        setmealService.savaWithDish(setmealDto);
        return R.success("新增套餐成功");
    }

    /*
     * 删除套餐
     * */
    @DeleteMapping
    @CacheEvict(value ="setmealCache",allEntries = true )
    public R delete(@RequestParam List<Long> ids) {
        log.info("ids{}", ids);
        setmealService.removeWithDish(ids);
        return R.success();
    }

    /*
     *     根据分类的id查询套餐列表
     * */
    @GetMapping("/list")
    @Cacheable(cacheNames = "setmealCache",key ="#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        log.info("根据分类的id查询套餐列表,setmeal={}", setmeal.toString());
        //组装条件，id , status;
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        //设置一个排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmeals = setmealService.list(queryWrapper);
        return R.success(setmeals);
    }

/*
* 修改状态
* */
    @PostMapping("/status/{status}")
    public R status(@RequestParam List<Long> ids, @PathVariable Integer status) {
        setmealService.status(ids, status);
        return R.success();
    }

    /**
     * 根据ID查询套餐数据
     */
    @GetMapping("/{id}")
    public R<SetmealDto> getById(@PathVariable Long id){
        log.info("根据ID查询套餐数据, id = {}", id);
        SetmealDto setmealDto = new SetmealDto();
        //获取套餐的基本信息
        Setmeal setmeal = setmealService.getById(id);
        BeanUtils.copyProperties(setmeal, setmealDto);
        //获取套餐关联的菜品列表
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper);
        setmealDto.setSetmealDishes(setmealDishList);
        return R.success(setmealDto);
    }

/*
* 修改
* */
    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info("接收页面传递的套餐数据, setmealDto= {}",setmealDto);
        setmealService.updateSetmeal(setmealDto);
        return R.success("更新成功");
    }

}
